// 导入模块
import axios from 'axios'
import router from '@/router'
// NOTE: 在非组件中使用store-需注意
import store from '@/store'
import Vue from 'vue'
import { Toast } from 'vant'
// import {getToken} from './getToken'
Vue.use(Toast)

// // 请求的默认地址
// const FH_API = process.env.VUE_APP_FH_API;
// // 认证的默认地址
// const authURL = process.env.VUE_APP_AUTH_API;
// // SSO的默认地址
// const sso_url = process.env.VUE_APP_SSO_URL;

// const baseURL = 'http://localhost:4000'
const baseURL = ''

// 设置请求的默认超时时间
axios.defaults.timeout = 360000;

// 拦截器配置 .. Interceptors
// Add a request interceptor 发送请求之前
axios.interceptors.request.use((config) => {
  // console.log(store.state.userModule.token)
  config.headers['accessToken'] = store.state.userModule.token;
  return config;
}, (error) => {
  Toast.fail('请求超时');
  return Promise.reject(error)
})

// Add a response interceptor 响应数据之后
axios.interceptors.response.use((response) => {
  const res = response.data;
  if (res.status < 0) {
    switch (res.code) {
      case 401:
        Toast.fail(res.msg)
        // sessionStorage.clear();
        router.push({ name: 'User-type', params: { type: 'login', redirect: window.location.href } });
        break;
      default:
        Toast.fail(res.msg)
        break;
    }
    store.commit('userModule/CHANGETOKEN', '')
    return Promise.reject(new Error("error is token invalid"));
  } else {
    return res;
  }
}, (error) => {
  console.log("response-error" + error);
  Toast.fail(res.msg)
  return Promise.reject(error)
})


// 封装请求函数
export const get = ({ url, data }) => {
  return axios({
    method: "GET",
    url: `${baseURL}${url}`,
    params: data
  });
};

export const post = ({ url, data }) => {
  return axios({
    method: "POST",
    url: `${baseURL}${url}`,
    data,
    headers: {
      "Content-Type": "application/json"
    }
  });
};

export const postFile = ({ url, data }) => {
  return axios({
    method: "POST",
    url: `${baseURL}${url}`,
    data,
    dataType: 'JSON',
    headers: {
      "Content-Type": "multipart/form-data"
    }
  });
};

export const put = ({ url, data }) => {
  return axios({
    method: "PUT",
    url: `${baseURL}${url}`,
    data,
    headers: {
      "Content-Type": "application/json"
    }
  });
};

export const del = ({ url, data }) => {
  return axios({
    method: "DELETE",
    url: `${baseURL}${url}`,
    params: data
  });
};

// export const downloadRequest = ({ url, data }) => {
//   return axios({
//     method: "post",
//     url: `${FH_API}${url}`,
//     responseType: "arraybuffer",
//     data: { ...data },
//     transformRequest: [
//       function (data) {
//         let ret = "";
//         for (let it in data) {
//           ret += encodeURIComponent(it) + "=" + encodeURIComponent(data[it]) + "&";
//         }
//         return ret;
//       }
//     ],
//     headers: {
//       "Content-Type": "application/x-www-form-urlencoded"
//     }
//   });
// };
